package com.mmlc.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.alipay.sdk.app.PayTask;
import com.allinpay.appayassistex.APPayAssistEx;
import com.androidnetframe.utils.LogUtils;
import com.google.gson.Gson;
import com.mmlc.meimei.lichengkongjian.been.Order;
import com.mmlc.meimei.lichengkongjian.been.PayResult;
import com.mmlc.network.responsebean.WXPayParams;
import com.tencent.mm.sdk.constants.Build;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;

import java.util.Map;

/**
 * Created by Administrator on 2016/8/16.
 */
public class PayUtils {
    Activity activity;
    Context context;

    public PayUtils(Activity activity) {
        this.activity = activity;
        this.context = activity.getApplicationContext();
    }

    public interface OnPayResultListener {

        /**
         * 1:alipay,2:weixin,3:union
         * 0:success,1:failure
         */
        void payResult(int payType, int payResult);
    }

    OnPayResultListener payResultListener;

    public void setPayResultListener(OnPayResultListener payResultListener) {
        this.payResultListener = payResultListener;
    }

    /**
     * 1:alipay,2:weixin,3:union
     * 0:success,1:failure
     */
    int pay_result = -1;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    LogUtils.e("Alipay","PayResult");
//                    PayResult payResult = new PayResult((String) msg.obj);
//                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
//
//                    String resultStatus = payResult.getResultStatus();
//                    if (TextUtils.equals(resultStatus, "9000")) {//支付成功
//                        pay_result = 0;
//                        LogUtils.e("Alipay","PayResult suc");
//                    } else {//支付失败
//                        pay_result = 1;
//                    }

                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        pay_result = 0;
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        pay_result = 1;
                    }
                    break;
                case 2:
                    pay_result = msg.arg1;
                    break;
                case 3:
                    pay_result = msg.arg1;
                    break;
                default:
                    break;
            }
            if (payResultListener != null) payResultListener.payResult(msg.what, pay_result);
        }
    };
    String wxpay_result;

    public void onResume() {
        wxpay_result = (String) SPUtils.get(context, "wxpay_result", "");
        if (!ViewUtils.isEmpty(wxpay_result)) {
            Message message = new Message();
            message.what = 2;
            if ("0".equals(wxpay_result)) {
                message.arg1 = 0;
            } else if (!ViewUtils.isEmpty(wxpay_result)) {
                message.arg1 = 1;
            }
            mHandler.sendMessage(message);
            SPUtils.put(context, "wxpay_result", "");
        }
    }

    Order order;

    public void toPay(Order order) {
        toPay(order, null);
    }

    public void toPay(Order order, OnPayResultListener payResultListener) {
        if (order == null) {
            ToastUtils.showToast("订单参数不完整");
            return;
        }

        LogUtils.e("Order", "Order:" + order.toString());

        this.order = order;
        if (!ViewUtils.isEmpty(order.getPay_code()) && "wxpay".equals(order.getPay_code())) {
            payByWeixin();
        } else if (!ViewUtils.isEmpty(order.getPay_code()) && "alipay".equals(order.getPay_code())) {
            payByAlipay();
        } else if (!ViewUtils.isEmpty(order.getPay_code()) && "xingwang".equals(order.getPay_code())) {
            payByUnion();
        }

        if (payResultListener != null) this.payResultListener = payResultListener;
    }

    private void payByWeixin() {
        if (ViewUtils.isEmpty(order.getPay_url())) {
            ToastUtils.showToast("订单参数不完整");
            return;
        }

        final IWXAPI api = WXAPIFactory.createWXAPI(context, Constants.WX_APP_ID, true);
        api.registerApp(Constants.WX_APP_ID);
        boolean isPaySupported = api.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT;
        if (!isPaySupported) {
            ToastUtils.showToast("你尚未安装可支付版本微信，请选择可支持设备支付");
            return;
        }

        XUtils.httpPost(context, order.getPay_url(), new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String s) {
                LogUtils.e("wx",s);
                try {
                    JSONObject json = new JSONObject(s);
                    if (json.optString("code").equals("0")) {
                        JSONObject data = json.optJSONObject("data");
                        if (data != null && !data.toString().equals("") && !data.toString().equals("null")) {
                            WXPayParams wxPayParams = new Gson().fromJson(data.toString(), WXPayParams.class);
                            PayReq req = new PayReq();
                            req.appId = wxPayParams.getAppid();
                            req.partnerId = wxPayParams.getPartnerid();
                            req.prepayId = wxPayParams.getPrepayid();
                            req.nonceStr = wxPayParams.getNoncestr();
                            req.timeStamp = wxPayParams.getTimestamp();
                            req.packageValue = wxPayParams.getPackageX();
                            req.sign = wxPayParams.getSign();
                            req.extData = "app data";
                            api.sendReq(req);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable throwable, boolean b) {
                ToastUtils.showToast("订单生成失败，请重试");
            }

            @Override
            public void onCancelled(CancelledException e) {
            }

            @Override
            public void onFinished() {
            }
        });
    }

    private void payByAlipay() {
        if (ViewUtils.isEmpty(order.getTitle()) || ViewUtils.isEmpty(order.getBody()) || ViewUtils.isEmpty(order.getOrder_price()) || ViewUtils.isEmpty(order.getNotify_url())) {
            ToastUtils.showToast("订单参数不完整");
            return;
        }
        final String payInfo = Alipay.getPayInfo(order.getOrder_id(),order.getTitle(), order.getBody(), order.getOrder_price(), order.getNotify_url());
        Runnable checkRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(activity);
                // 调用支付接口，获取支付结果
//                String result = alipay.pay(payInfo, true);
                LogUtils.e("Alipay","result start"+payInfo);
                Map<String, String> result = alipay.payV2(payInfo, true);
                LogUtils.e("Alipay","result:"+result.toString());
                Message msg = new Message();
                msg.what = 1;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread checkThread = new Thread(checkRunnable);
        checkThread.start();
    }

    /**
     * 银联支付
     */
    private void payByUnion() {
        if (ViewUtils.isEmpty(order.getOrder_id())|| ViewUtils.isEmpty(order.getTitle())|| ViewUtils.isEmpty(order.getOrder_price()) || ViewUtils.isEmpty(order.getNotify_url())|| ViewUtils.isEmpty(order.getExt1())) {
            ToastUtils.showToast("订单参数不完整");
            return;
        }

        JSONObject payData = PaaCreator.randomPaa(order.getOrder_id(),order.getTitle(), order.getOrder_price(), order.getNotify_url(),order.getExt1());
        APPayAssistEx.startPay(activity, payData.toString(), APPayAssistEx.MODE_PRODUCT);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == APPayAssistEx.REQUESTCODE) {
            if (null != data) {
                String payRes = null;
                String payAmount = null;
                String payTime = null;
                String payOrderId = null;
                try {
                    JSONObject resultJson = new JSONObject(data.getExtras()
                            .getString("result"));
                    payRes = resultJson.getString(APPayAssistEx.KEY_PAY_RES);
                    payAmount = resultJson.getString("payAmount");
                    payTime = resultJson.getString("payTime");
                    payOrderId = resultJson.getString("payOrderId");
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                Message message = new Message();
                message.what = 3;
                if (null != payRes && payRes.equals(APPayAssistEx.RES_SUCCESS)) {
                    message.arg1 = 0;
                } else {
                    message.arg1 = 1;
                }
                mHandler.sendMessage(message);

                LogUtils.e("payResult", "payResult:" + data.getExtras()
                        .getString("result") + " payRes: " + payRes + "  payAmount: "
                        + payAmount + "  payTime: " + payTime
                        + "  payOrderId: " + payOrderId);
            }
        }
    }
}
